package com.arnold.www.lock;

import com.arnold.www.atomic.AtomicTest;
import com.arnold.www.atomic.User;

import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.concurrent.atomic.AtomicIntegerArray;
import java.util.concurrent.atomic.AtomicIntegerFieldUpdater;
import java.util.concurrent.atomic.AtomicReference;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

/**
 * @ClassName Lock_test
 * @Description: lock接口的简单使用
 * @Author Arnold
 * @Date 2020/4/12
 * @Version V2.0
 **/
public class Lock_test {

    private int value = 0;

    //定义一把锁
    Lock lock = new ReentrantLock();

    public int getValue(){
        //加锁
        lock.lock();
        value++;
        //释放锁
        lock.unlock();
        return  value;
    }

    public static void main(String[] args) {
        final Lock_test lockTest =new Lock_test();

        ExecutorService executorService = Executors.newFixedThreadPool(2);
        executorService.submit(new Runnable() {
                    public void run() {
                        for (int i=0;i<10;i++) {
                            System.out.println(Thread.currentThread().getName()+"\t"+lockTest.getValue());
                            try {
                                Thread.sleep(100);
                            } catch (InterruptedException e) {
                                e.printStackTrace();
                            }
                        }
                    }
        });
        executorService.submit(new Runnable() {
                    public void run() {
                        for (int i=0;i<10;i++) {
                            System.out.println(Thread.currentThread().getName()+"\t"+lockTest.getValue());
                            try {
                                Thread.sleep(100);
                            } catch (InterruptedException e) {
                                e.printStackTrace();
                            }
                        }
                    }
        });
        executorService.shutdown();
    }
}